<template>
  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="35%" align-center>
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="列名称" prop="name">
            <ElInput v-model="formData.name" placeholder="请输入列名称" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="列描述" prop="comment">
            <ElInput v-model="formData.comment" placeholder="请输入列描述" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="SQLA类型" prop="type">
            <ElInput v-model="formData.type" placeholder="请输入SQLA模型列类型" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="Pydantic类型" prop="pd_type">
            <ElInput v-model="formData.pd_type" placeholder="请输入Pydantic类型" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="默认值" prop="default">
            <ElInput v-model="formData.default" placeholder="请输入默认值" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="排序" prop="sort">
            <ElInputNumber v-model="formData.sort" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="长度" prop="length">
            <ElInputNumber v-model="formData.length" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="主键" prop="is_pk">
            <ElSwitch v-model="formData.is_pk" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="可为空" prop="is_nullable">
            <ElSwitch v-model="formData.is_nullable" />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElRow, ElCol, ElDialog, ElForm, ElFormItem, ElInput, ElInputNumber, ElSwitch } from 'element-plus'
import { createGenColumn, updateGenColumn } from '@/api/code_generator/gen_column'
import type { GenColumn, GenColumnCreate, GenColumnUpdate } from '@/api/code_generator/gen_column'

interface Props {
  visible: boolean
  type: 'add' | 'edit'
  editData?: GenColumn
  businessId: number
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const dialogTitle = computed(() => (props.type === 'add' ? '新增字段' : '编辑字段'))

const formRef = ref<FormInstance>()

const getInitialFormData = (): GenColumnCreate => ({
  name: '',
  comment: '',
  type: '',
  pd_type: '',
  default: '',
  sort: 0,
  length: 0,
  is_pk: false,
  is_nullable: true,
  gen_business_id: props.businessId
})

const formData = reactive<GenColumnCreate | GenColumnUpdate>(getInitialFormData())

const rules: FormRules = {
  name: [{ required: true, message: '请输入列名称', trigger: 'blur' }],
  type: [{ required: true, message: '请输入SQLA模型列类型', trigger: 'blur' }],
  pd_type: [{ required: true, message: '请输入Pydantic类型', trigger: 'blur' }],
  length: [{ required: true, message: '请输入长度', trigger: 'blur' }]
}

const initFormData = () => {
  if (props.type === 'edit' && props.editData) {
    Object.assign(formData, props.editData)
  } else {
    Object.assign(formData, getInitialFormData())
  }
}

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      initFormData()
      nextTick(() => formRef.value?.clearValidate())
    }
  },
  { immediate: false }
)

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (props.type === 'add') {
        await createGenColumn(formData as GenColumnCreate)
        ElMessage.success('新增成功')
      } else {
        await updateGenColumn(props.editData?.id || 0, formData as GenColumnUpdate)
        ElMessage.success('更新成功')
      }
      emit('submit')
      dialogVisible.value = false
    } catch (error: any) {
      console.error(error)
    }
  })
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>